'use client';

import { useEffect, useState } from 'react';
import { Form, DatePicker, Button, Card, Typography, Message, Spin, InputNumber } from '@arco-design/web-react';
import { useRouter, useSearchParams } from 'next/navigation';
import { useAuth } from '@/contexts/AuthContext';
import { roomApi, bookingApi } from '@/services/api';
import { Room, Booking } from '@/types';

const FormItem = Form.Item;
const { Title, Text } = Typography;
const { RangePicker } = DatePicker;

export default function CreateBookingPage() {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [roomLoading, setRoomLoading] = useState(true);
  const [room, setRoom] = useState<Room | null>(null);
  const [totalDays, setTotalDays] = useState(1);
  const [totalAmount, setTotalAmount] = useState(0);

  const router = useRouter();
  const searchParams = useSearchParams();
  const roomId = searchParams.get('roomId');

  const { user, userType, isAuthenticated } = useAuth();

  useEffect(() => {
    // 如果未登录或不是客户，重定向到登录页
    if (!isAuthenticated) {
      router.push('/login');
      return;
    }

    if (userType !== 'customer') {
      router.push('/');
      return;
    }

    // 如果没有房间ID，重定向到房间列表
    if (!roomId) {
      router.push('/rooms');
      return;
    }

    // 获取房间信息
    const fetchRoomData = async () => {
      setRoomLoading(true);
      try {
        const response = await roomApi.getById(parseInt(roomId));
        if (response.code === 200 && response.data) {
          setRoom(response.data);
          // 设置初始总金额
          setTotalAmount(response.data.price);
        } else {
          // Message.error(response.message || '获取房间信息失败');
          router.push('/rooms');
        }
      } catch (error) {
        console.error('获取房间信息错误:', error);
        // Message.error('获取房间信息时发生错误');
        router.push('/rooms');
      } finally {
        setRoomLoading(false);
      }
    };

    fetchRoomData();
  }, [isAuthenticated, userType, roomId, router]);

  const handleDateChange = (dates: any) => {
    if (dates && dates.length === 2 && room) {
      // 计算天数差
      const startDate = new Date(dates[0]);
      const endDate = new Date(dates[1]);
      const diffTime = Math.abs(endDate.getTime() - startDate.getTime());
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

      setTotalDays(diffDays);
      setTotalAmount(diffDays * room.price);
    }
  };

  const handleSubmit = async (values: any) => {
    if (!room || !user || userType !== 'customer') return;

    setLoading(true);
    try {
      // 准备预订数据
      const bookingData = {
        roomId: room.roomId!,
        checkInTime: values.dateRange[0],
        checkOutTime: values.dateRange[1],
        totalAmount: totalAmount
      };

      console.log('提交的预订数据:', bookingData);

      // 调用创建预订 API
      const response = await bookingApi.create(bookingData);

      if (response.code === 200) {
        Message.success('预订成功');
        router.push('/bookings');
      } else {
        // Message.error(response.message || '预订失败，请稍后重试');
      }
    } catch (error) {
      console.error('预订错误:', error);
      // Message.error('预订过程中发生错误');
    } finally {
      setLoading(false);
    }
  };

  if (roomLoading) {
    return (
      <div className="flex justify-center items-center min-h-[60vh]">
        <Spin />
      </div>
    );
  }

  if (!room) {
    return null;
  }

  return (
    <div className="max-w-2xl mx-auto py-8">
      <Card className="shadow-md">
        <div className="text-center mb-6">
          <Title heading={3}>预订房间</Title>
          <Text type="secondary">请填写预订信息</Text>
        </div>

        <div className="mb-6 p-4 bg-gray-50 rounded">
          <Title heading={5}>房间信息</Title>
          <div className="grid grid-cols-2 gap-4 mt-2">
            <div>
              <Text type="secondary">房间号:</Text>
              <div><Text bold>{room.roomNumber}</Text></div>
            </div>
            <div>
              <Text type="secondary">房间类型:</Text>
              <div><Text bold>{room.roomType}</Text></div>
            </div>
            <div>
              <Text type="secondary">价格:</Text>
              <div><Text bold type="success">¥{room.price}/晚</Text></div>
            </div>
            <div>
              <Text type="secondary">状态:</Text>
              <div><Text bold>{room.status}</Text></div>
            </div>
          </div>
        </div>

        <Form
          form={form}
          layout="vertical"
          onSubmit={handleSubmit}
          initialValues={{
            guests: 1
          }}
        >
          <FormItem
            label="入住和退房日期"
            field="dateRange"
            rules={[{ required: true, message: '请选择入住和退房日期' }]}
          >
            <RangePicker
              style={{ width: '100%' }}
              onChange={handleDateChange}
              disabledDate={(current) => current.isBefore(new Date(), 'day')}
            />
          </FormItem>

          <FormItem
            label="入住人数"
            field="guests"
            rules={[{ required: true, message: '请输入入住人数' }]}
          >
            <InputNumber
              min={1}
              max={4}
              style={{ width: '100%' }}
            />
          </FormItem>

          <div className="mb-6 p-4 bg-blue-50 rounded">
            <div className="flex justify-between items-center">
              <Text>住宿天数:</Text>
              <Text bold>{totalDays}晚</Text>
            </div>
            <div className="flex justify-between items-center mt-2">
              <Text>总价:</Text>
              <Text bold type="success" style={{ fontSize: '18px' }}>¥{totalAmount}</Text>
            </div>
          </div>

          <FormItem>
            <div className="flex space-x-4">
              <Button
                type="primary"
                htmlType="submit"
                long
                loading={loading}
              >
                确认预订
              </Button>
              <Button
                type="secondary"
                long
                onClick={() => router.push('/rooms')}
              >
                返回
              </Button>
            </div>
          </FormItem>
        </Form>
      </Card>
    </div>
  );
}